<template>
  <n-select
    class="my-role-select"
    v-model:value="value"
    :multiple="multiple"
    :filterable="filterable"
    :options="options"
    @update:value="handleValueChange"
    :class="className"
    placeholder="选择角色"
    :to="to"
    :size="size"
    :render-label="renderLabel"
    :render-tag="multiple ? renderMultipleSelectTag : undefined"
    :placement="placement"
  />
</template>

<script setup lang="ts">
import type { VNodeChild } from 'vue'
import type { SelectRenderTag } from 'naive-ui'
import type { CommonOpt } from '@/types/commom'
import useRoleStore from '@/stores/modules/role'
import { renderRoleLabel, renderTag } from '@/utils/commonBusiness'

const props = withDefaults(
  defineProps<{
    roleType?: number
    multiple?: boolean
    filterable?: boolean
    className?: any
    size?: 'tiny' | 'small' | 'medium' | 'large'
    defaultRoleId?: string
    defaultRoleIds?: string[]
    to?: string | boolean
    placement?: string
  }>(),
  {
    roleType: 0,
    multiple: true,
    filterable: true,
    size: 'small',
    className: {
      '!min-w-[300px]': true,
      'w-[300px]': true
    },
    to: 'body',
    placement: 'bottom-start'
  }
)

const emits = defineEmits<{
  (e: 'changeValue', value: string | string[]): void
}>()

const roleStore = useRoleStore()

const value = ref<string | string[]>([])
const options = ref<CommonOpt[]>([])

watch(
  props,
  (newValue) => {
    if (props.multiple) {
      value.value = newValue.defaultRoleIds || []
    } else {
      value.value = newValue.defaultRoleId || '4'
    }
  },
  {
    deep: true,
    immediate: true
  }
)

const renderLabel = (option: CommonOpt): VNodeChild => {
  return renderRoleLabel(option.color as string, option.label as string)
}

const renderMultipleSelectTag: SelectRenderTag = ({ option, handleClose }) => {
  return renderTag(option, handleClose, () =>
    renderRoleLabel(option.color as string, option.label as string)
  )
}

// 初始化角色列表数据
const initOptions = async () => {
  if (!roleStore.roleList.length) {
    await roleStore.getRoleList()
  }

  options.value = roleStore.roleList
    .filter((item) => +item.type === props.roleType)
    .map((item) => {
      return {
        label: item.name,
        value: item.id,
        color: item.label,
        disabled: !item.isVisible
      }
    })

  if (options.value.length) {
    value.value = options.value[0].value as string
  }
  if (props.defaultRoleId) {
    value.value = props.defaultRoleId || '4'
  }
  if (props.defaultRoleIds) {
    value.value = props.defaultRoleIds || []
  }
}

// 将变化后的传递给父组件
const handleValueChange = (value: string | string[]) => {
  emits('changeValue', value)
}

onMounted(() => {
  initOptions()
})
</script>

<style scoped lang="scss"></style>
